precision mediump float;

attribute vec3 a_position;
attribute vec3 a_normal;

uniform mat4 projMatrix;
uniform mat4 mvMatrix;
uniform mat4 viewMatrix;

// 方向光
uniform vec3 lightDir;
uniform float dirLightIntensity;
varying vec3 vDiffuseColor;
varying vec3 vSpecColor;

// 镜面光
uniform float shiness;

void main() {

    vec4 posInV = mvMatrix * vec4(a_position, 1.0);

    // 相机空间中 光方向
    vec3 lightDirInV = normalize((viewMatrix * vec4(lightDir, 0.0)).xyz);

    // 相机空间中的法线
    vec3 normalInV = normalize((mvMatrix * vec4(a_normal, 0.0)).xyz);
    float diffuse = max(0.0,dot(normalInV,lightDirInV));
    vDiffuseColor = dirLightIntensity * diffuse * vec3(1.0,1.0,1.0);

    // 计算镜面光
    vec3 posToCamera = normalize(-posInV.xyz);
    vec3 refLight = normalize(reflect(-lightDirInV,normalInV));
    float spec = max(0.0,dot(refLight,posToCamera));
    if(spec > 0.0){
        spec = pow(spec,shiness);
    }
    vSpecColor = spec * vec3(1.0,1.0,1.0);

    gl_Position = projMatrix * posInV;
}
